import { Common } from 'cby.assist'
import SystemApi from '@/api/SystemApi'
import main from '@/views/main/'
import layout from '@/views/main/Layout'
import Error404 from '@/views/module/erro-page/404.vue'
import router, { resetRouter } from '@/router'

let isFirst = true

/** 路由组件 */
// const ROUTE_COMP = {
//   template:
//     '<div><transition name="move" mode="out-in"><router-view/></transition></div>'
// }

/**
 * 加载视图组件
 */
const loadView = view => () => import(`@/views/module${view}`)

/**
 * 创建路由
 */
function createRoute(menu, component) {
  const route = {
    name: '主体',
    path: '',
    component,
    children: []
  }
  menu.map(item => route.children.push(toRoute(item)))
  return route
}

/**
 * 增加路由属性
 */
function toRoute(item) {
  item.name = item.enName
  // item.component = item.funcType === 'MENU' ? loadView(item.path) : ROUTE_COMP
  item.component = item.funcType === 'MENU' ? loadView(item.path) : layout
  if (item.children && item.children.length) {
    item.children.forEach(subItem => {
      subItem.meta = {
        parent: item.enName
      }
      toRoute(subItem)
    })
  }
  return item
}

const errorPage = [
  {
    path: '/404',
    name: 'ERROR404',
    component: Error404
  },
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

/**
 * 菜单
 */
export default {
  state: {
    menu: [],
    navMenuDefaultActive: '', // 当前选中路由
    activedTabs: [ // tab
      {
        label: 'HOME',
        name: 'HOME',
        path: '/index'
      }
    ],
    tabsType: 'tab-nav' // 导航模式
  },
  getters: {
    getMenu: state => state.menu, // 获取菜单信息
    getMenuItem: state => menuId => Common.recursiveQuery(menuId, state.menu, 'funcId'), // 获取菜单项
    getActivedTabs: state => state.activedTabs,
    getCurrentTab: state => state.navMenuDefaultActive,
    getTabsType: state => state.tabsType
  },
  actions: {
    // 加载菜单数据
    loadMenu: ({ commit }, params) => {
      SystemApi.menu(params).then(res => {
        const menu = res || []
        console.log('SystemApi.menu', menu)
        const route = createRoute(menu, main)
        resetRouter() // 重置路由
        router.addRoute(route)
        errorPage.forEach(item => {
          router.addRoute(item)
        })
        commit('setMenu', menu)
      }).catch(err => {
        console.log('SystemApi.menu', err)
      })
    }
  },
  mutations: {
    setMenu: (state, menu) => { // 设置菜单项
      state.menu = menu.filter(i => i.name !== 'HOME') // 不显示首页菜单
      // 判断权限 移除tabs
      const tabs = localStorage.oenActivedTabs
      if (tabs) {
        const navs = JSON.parse(tabs)
        const menuName = ['HOME']
        const menuFn = (children) => {
          children.forEach(item => {
            menuName.push(item.name)
            if (item.children && item.children.length) {
              menuFn(item.children)
            }
          })
        }
        menuFn(menu)
        state.activedTabs = navs.filter(item => menuName.includes(item.name))
      } else {
        state.navMenuDefaultActive = state.activedTabs[0]['name']
      }
      setStorage(state)
    },
    setTabType: (state, tab) => (state.tabsType = tab), // 导航模式
    clearMenu: state => (state.menu = []), // 清除菜单数据
    deleteTabs: (state, index) => { // 删除tab
      state.activedTabs.splice(index, 1)
      setStorage(state)
    },
    del_others_visited_views: (state, view) => { // 关闭其他tab
      state.activedTabs = state.activedTabs.filter(v => {
        return v.name === view.name || v.name === 'HOME'
      })
      setStorage(state)
    },
    del_right_visited_views: (state, index) => { // 关闭右边tab
      state.activedTabs = state.activedTabs.filter((v, i) => {
        return i <= index
      })
      setStorage(state)
    },
    addActivedTabs: (state, item) => {
      if (router.currentRoute.path !== item.path) {
        if (sessionStorage.oenActivedTabs) {
          state.activedTabs = JSON.parse(sessionStorage.oenActivedTabs)
          isFirst = false
        }
        if (isFirst && localStorage.oenActivedTabs) {
          state.activedTabs = JSON.parse(localStorage.oenActivedTabs)
          isFirst = false
        }
        const itemIndex = state.activedTabs.findIndex((obj) => obj.name === item.name)
        if (itemIndex < 0) {
          state.activedTabs.push(item)
        }
        state.navMenuDefaultActive = item.name
        setStorage(state)
      } else {
        state.navMenuDefaultActive = item.name
      }
    }
  }
}

function setStorage(state) {
  sessionStorage.setItem('oenActivedTabs', JSON.stringify(state.activedTabs))
  localStorage.setItem('oenActivedTabs', JSON.stringify(state.activedTabs))
}
